import { Table, Modal, message, Row, Col, Space, Popconfirm, Badge, Tooltip } from "antd";
import { Card as SemiCard, List, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh, IconEyeOpened, IconPlus, IconEdit, IconGlobeStroke } from "@douyinfe/semi-icons";
import { useModel } from "umi";

import useAllPersonVersions from "../../hooks/referenceDatabase/useAllPersonVersions";
import useAddPersonVersion from "../../hooks/referenceDatabase/useAddPersonVersion";
import usePublishPersonVersion from "../../hooks/referenceDatabase/usePublishPersonVersion";

const { Column } = Table;

const PersonReferenceDatabase = () => {
    const { windowInnerHeight, BNTApplicationOperationCenterUrls, runEnv } = useModel("global");
    const { setModalVisible, setModalTitle, setModalWidth, setModalComponent } = useModel("global.modal");

    const { loading, loadVersions, versions } = useAllPersonVersions();
    const { addVersion } = useAddPersonVersion();
    const { loading: submitLoading, publishVersion } = usePublishPersonVersion();

    const openDataDetail = (record) => {
        setModalTitle("查看补丁数据");
        setModalWidth(650);
        setModalComponent(<DataDetailModal record={record} />);
        setModalVisible(true);
    };

    const onlineRunEnv = {
        development: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        dev: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        testing: [
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
            { title: "生产环境", runEnv: "production", url: BNTApplicationOperationCenterUrls.production },
        ],
        production: [],
    };

    const renderPatchData = (_, r, i) => _ && _.length > 0 && <Button theme="borderless" icon={<IconEyeOpened />} onClick={() => openDataDetail(_)}></Button>;

    const renderPublishRecord = (_, r, i) => (
        <Space>
            <Tooltip title={_["dev"]?.uuid ? `${_["dev"]?.name} ${formatUTCTime(_["dev"]?.time)}` : ""}>
                <Badge color={_["dev"]?.uuid ? "green" : "red"} />
            </Tooltip>
            <Tooltip title={_["testing"]?.uuid ? `${_["testing"]?.name} ${formatUTCTime(_["testing"]?.time)}` : ""}>
                <Badge color={_["testing"]?.uuid ? "green" : "red"} />
            </Tooltip>
            <Tooltip title={_["production"]?.uuid ? `${_["production"]?.name} ${formatUTCTime(_["production"]?.time)}` : ""}>
                <Badge color={_["production"]?.uuid ? "green" : "red"} />
            </Tooltip>
        </Space>
    );

    const renderOperate = (_, r) => (
        <Space size={0}>
            {onlineRunEnv[runEnv].map((item, index) => (
                <Popconfirm
                    key={index}
                    placement="topRight"
                    title={`确认要发布数据库版本到应用运营中心吗?`}
                    okButtonProps={{ loading: submitLoading }}
                    onConfirm={() =>
                        publishVersion(item, r, (res) => {
                            if (res) {
                                message.success("数据库版本发布成功");
                                loadVersions();
                            }
                        })
                    }
                >
                    <Button key={index} theme="borderless" icon={<IconGlobeStroke />} title={`发布到${item.title}`}></Button>
                </Popconfirm>
            ))}
        </Space>
    );

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>个人参考数据库结构版本列表</span>}
            headerExtraContent={
                <ButtonGroup>
                    <Button
                        icon={<IconPlus />}
                        onClick={() =>
                            addVersion((res) => {
                                if (res) {
                                    message.success("成功添加版本信息");
                                    loadVersions();
                                }
                            })
                        }
                    ></Button>
                    <Button icon={<IconRefresh />} onClick={loadVersions}></Button>
                </ButtonGroup>
            }
            headerStyle={{ padding: "10px 14px" }}
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
            style={{ margin: 10 }}
        >
            <Table loading={loading} dataSource={versions} rowKey="uuid" bordered size="small" pagination={false} scroll={{ y: cardBodyHeight - 40 }}>
                <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                <Column title="版本号" dataIndex="versionNo" align="center" />
                <Column title="创建人" dataIndex="creater" align="center" render={(_, r, i) => _.name} />
                <Column title="创建时间" dataIndex="createTime" align="center" render={(_, r, i) => formatUTCTime(_)} />
                <Column title="补丁数据" dataIndex="patchData" align="center" render={renderPatchData} />
                <Column title="比较的版本号" dataIndex="compareVersion" align="center" />
                <Column title="发布状态" dataIndex="publishRecord" align="center" render={renderPublishRecord} />
                <Column title="操作" align="center" width={120} render={renderOperate} />
            </Table>
        </SemiCard>
    );
};

const DataDetailModal = ({ record }) => {
    return (
        <div>
            <List
                bordered
                dataSource={record}
                renderItem={(item) => (
                    <List.Item>
                        <div>{item}</div>
                    </List.Item>
                )}
            />
        </div>
    );
};

export default PersonReferenceDatabase;
